﻿using MVVMPattern.Base;
using MVVMPattern.Models;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MVVMPattern.ViewModels
{
    public class MainViewModel
    {
        public DataModel Data { get; set; }

        public ObservableCollection<ResultModel> ResultList { get; set; } = new ObservableCollection<ResultModel>();

        public Command ClickMeCommand { get; set; }

        /// <summary>
        /// 删除ListBox中的子项的命令
        /// </summary>
        public Command ResultDeleteCommand { get; set; }

        public MainViewModel()
        {
            Data = new DataModel();
            #region 两种方式都可以
            //ClickMeCommand = new Command(DoClick, CanClick);
            ClickMeCommand = new Command(new Action<object?>(DoClick), new Func<object?, bool>(CanClick));
            #endregion

            ResultDeleteCommand = new Command((object? parameter) =>
            {
                ResultList.Remove((ResultModel)parameter);
            });

            Data.PropertyChanged += Value1_PropertyChanged;
        }

        private void Value1_PropertyChanged(object? sender, PropertyChangedEventArgs e)
        {
            if (new string[] { "Value1", "Value2" }.Contains(e.PropertyName))
            {
                ClickMeCommand.RaiseCanExecuteChanged();
            }
        }

        public void DoClick(object? parameter)
        {
            Data.Value3 = Data.Value2 + Data.Value1 + int.Parse(parameter.ToString());




            // 这里不通知是无法在界面上显示的！
            // 需要什么类型的通知？通知的对象是谁？
            // 1、这个动作肯定不会触发ResultList属性的Set方法！！！！！
            //    ResultList = new List<string>(); 这个会触发！！！！
            // 2、如果希望通知子项的变化（这个集合中的子项的增减），
            //    需要实现INofityCollectionChanged接口，进行子项变化通知

            ResultModel resultModel = new ResultModel(ResultList);
            resultModel.Msg = $"{Data.Value2} + {Data.Value1} + {parameter} = {Data.Value3}";
            ResultList.Add(resultModel);
        }

        public bool CanClick(object? parameter)
        {
            // TODO: Add code to check if the button can be clicked.
            if (Data.Value1 > 0 && Data.Value2 > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}
